package com.qf.ability.test.service.impl;

import com.qf.ability.test.entity.Goods;
import com.qf.ability.test.service.IGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.data.elasticsearch.core.query.UpdateResponse;
import org.springframework.stereotype.Service;

/**
 * author Ken
 * create_time 2022/9/7
 */
@Service
public class GoodsServiceImpl implements IGoodsService {

    @Autowired
    private ElasticsearchRestTemplate restTemplate;

    /**
     * 创建索引库
     * @return
     */
    @Override
    public boolean createIndex() {
        IndexOperations indexOperations = restTemplate.indexOps(Goods.class);
        return indexOperations.create();
    }

    /**
     * 创建映射类型
     * @return
     */
    @Override
    public boolean createMapping() {
        IndexOperations indexOperations = restTemplate.indexOps(Goods.class);
        Document document = indexOperations.createMapping();
        return indexOperations.putMapping(document);
    }

    /**
     * 添加文档
     * @param goods
     * @return
     */
    @Override
    public boolean addGoods(Goods goods) {
        Goods result = restTemplate.save(goods);
        return result != null;
    }

    /**
     * 根据id修改商品信息
     * @param id
     * @param key
     * @param value
     * @return
     */
    @Override
    public boolean updateGoods(Integer id, String key, Object value) {


        Document document = Document.create();
        document.put(key, value);
        UpdateQuery updateQuery = UpdateQuery.builder(id + "")
                .withDocument(document)
                .build();

        UpdateResponse updateResponse = restTemplate.update(updateQuery, IndexCoordinates.of("goods_index"));
        System.out.println("修改的结果：" + updateResponse);
        return updateResponse.getResult().ordinal() == 1;
    }

    /**
     * 根据id删除商品
     * @param id
     * @return
     */
    @Override
    public boolean deteleGoods(Integer id) {
        String delete = restTemplate.delete(id + "", IndexCoordinates.of("goods_index"));
        System.out.println("删除的结果：" + delete);
        return true;
    }

}
